package com.un.web.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Page;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.un.core.cache.RedisCache;
import com.un.core.common.ComConstants;
import com.un.core.utils.*;
import com.un.web.sys.domain.entity.SysRole;
import com.un.web.sys.domain.entity.SysUser;
import com.un.web.sys.domain.vo.SysUserVO;
import com.un.web.sys.service.SysRoleService;
import com.un.web.sys.mapper.SysUserMapper;
import com.un.web.sys.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author xingjian
 * @Date 2023-01-12
 **/

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return sysUserMapper.deleteById(id);
    }

    @Override
    public HashMap<String, String> getQrCode() {
       // SnowFlake snowFlake = new SnowFlake(1,1,1);
        HashMap<String, String> map = new HashMap<>();
        try {
            String result = HttpClientUtils.get("https://server01.vicy.cn/8lXdSX7FSMykbl9nFDWESdc6zfouSAEz/wxlogin/wxLogin/tempUserId?secretKey=8a4fad25dafa42b6a7a90dcb29c452e3");
            HashMap hashMap = JSONObject.parseObject(result, HashMap.class);
            HashMap data = JSONObject.parseObject(hashMap.get("data").toString(), HashMap.class);
            redisCache.setCacheObject("wx:"+data.get("tempUserId"),true,1,TimeUnit.MINUTES);
            map.put("qrCodeReturnUrl",data.get("qrCodeReturnUrl").toString());
            map.put("temUserId",data.get("tempUserId").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public boolean saveUser(SysUser record) {
        String salt = MD5Util.getSalt();
        record.setSalt(salt);
        record.setPassword(MD5Util.getSaltMD5(ComConstants.InitPassword, salt));
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<SysUser>().eq("name", record.getName());
        List<SysUser> sysUsers = sysUserMapper.selectList(userQueryWrapper);
        if (sysUsers.size()>0&&record.getId()==null){
            return false;
        }
        return super.saveOrUpdate(record);
    }

    @Override
    public SysUser selectByPrimaryKey(Integer id) {
        return sysUserMapper.selectById(id);
    }

    @Override
    public int updateByPrimaryKeySelective(SysUser record) {
        return sysUserMapper.updateById(record);
    }

    @Override
    public int updateByPrimaryKey(SysUser record) {
        return sysUserMapper.updateById(record);
    }

    @Override
    public PageInfo<SysUserVO> selectAllByPage(Page page, SysUser user) {
        PageHelper.startPage(page.getPageNumber(),page.getPageSize());
        List<SysUserVO> sysUserVos = sysUserMapper.selectAllUser(user);
        return new PageInfo<>(sysUserVos);
    }

    @Override
    public HashMap<String, Object> login(SysUser user) {
        HashMap<String, Object> result = new HashMap<>();
        SysUser dataUser = null;
        try {
            dataUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("mobile", user.getMobile()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StrUtil.isEmptyIfStr(dataUser)){
            result.put("msg","未查询到当前用户");
            return result;
        }
        if (MD5Util.getSaltVerifyMD5(user.getPassword(),dataUser.getPassword(),dataUser.getSalt())){
            String token = TokenUtils.getToken(dataUser.getId().toString(), dataUser.getPassword());
            result.put("token",token);
            SysRole sysRole = sysRoleService.getSysRoleById(dataUser.getRoleId());
            SysUserVO sysUserVo = new SysUserVO();
            BeanUtils.copyProperties(dataUser,sysUserVo);
            sysUserVo.setSysRole(sysRole);
            result.put("user", sysUserVo);
            try {
                redisCache.setCacheObject("sys:user:token:"+dataUser.getId(),token,20, TimeUnit.MINUTES);
            } catch (Exception e) {
                HashMap<String, Object> msg = new HashMap<>();
                msg.put("msg","页面超时");
                e.printStackTrace();
                return msg;
            }
            return result;
        }
        result.put("msg","密码错误");
        return result;
    }

    @Override
    public List<SysUser> selectAll() {
        return sysUserMapper.selectList(null);
    }

    @Override
    public void loginOut(Integer id) {
        redisCache.deleteObject("sys:user:token:"+id);
    }

    @Override
    public SysUser selectWxUser(String userId) {
        return sysUserMapper.selectUserByWxUserid(userId);
    }

    @Override
    public HashMap<String, Object> loginWx(String temUserId) {
        boolean flag=true;
        long startTime = System.currentTimeMillis();
        while (flag){
            Object cacheObject = redisCache.getCacheObject("wx:" + temUserId);
            if (StrUtil.isEmptyIfStr(cacheObject)){
                flag=false;
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            long endTime = System.currentTimeMillis();
            if(endTime - startTime > 10000){
                break;
            }
        }
        if (flag){
            return null;
        }
        SysUser sysUser=sysUserMapper.selectUserByTempId(temUserId);
        if (StrUtil.isEmptyIfStr(sysUser)){
            return null;
        }
        HashMap<String, Object> result = new HashMap<>();
        String token = TokenUtils.getToken(sysUser.getId().toString(), sysUser.getPassword());
        result.put("token",token);
        SysRole sysRole = sysRoleService.getSysRoleById(sysUser.getRoleId());
        SysUserVO sysUserVo = new SysUserVO();
        BeanUtils.copyProperties(sysUser,sysUserVo);
        sysUserVo.setSysRole(sysRole);
        result.put("user", sysUserVo);
        try {
            redisCache.setCacheObject("sys:user:token:"+sysRole.getId(),token,20, TimeUnit.MINUTES);
        } catch (Exception e) {
            HashMap<String, Object> msg = new HashMap<>();
            msg.put("msg","页面超时");
            e.printStackTrace();
            return msg;
        }
        return result;
    }

}









